#include<iostream>
#include<pthread.h>
#include <unistd.h>
using namespace std;

int ticket = 1000;
//pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;  //静态分配,不需要销毁
pthread_mutex_t mtx_d;   //动态锁，需要用函数初始化
void * func(void* args)
{
    char *id = (char *)args;
    while(true)
    {
        //抢票前加锁
        //pthread_mutex_lock(&mtx);
        pthread_mutex_lock(&mtx_d);
        if(ticket>0)
        {
            //usleep(1000);
            ticket--;
            cout<<id<<" 抢票， ticket："<<ticket<<endl;
            //抢完票解锁
            //pthread_mutex_unlock(&mtx);   
            pthread_mutex_unlock(&mtx_d);   
        }
        else
        {
            //抢完票解锁
            //pthread_mutex_unlock(&mtx); 
            pthread_mutex_unlock(&mtx_d);
            break;
        }
        usleep(1000);    //抢完票干点别的
    } 
    return nullptr;
}


int main()
{
    pthread_t t1, t2, t3, t4;
    pthread_mutex_init(&mtx_d,nullptr);


    pthread_create(&t1,nullptr, func,(void *)"thread 1");
    pthread_create(&t2,nullptr, func,(void *)"thread 2");
    pthread_create(&t3,nullptr, func,(void *)"thread 3");
    pthread_create(&t4,nullptr, func,(void *)"thread 4");

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);
    pthread_join(t4, nullptr);

    pthread_mutex_destroy(&mtx_d);   //动态分配要销毁锁
    return 0;
}